﻿using Bystd.Geo.Geometries;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Bystd.Geo.GeoParsers.Shpfile
{
    public class ShxReader:BaseFile
    {
        public ShxReader(string shxFile)
            :base(shxFile)
        {

        }

        public ShxInfo Reader()
        {
            ShxInfo shx = new ShxInfo();

            var reader = BinReaderStream();

            reader.ReadBytes(24);
            byte[] l = reader.ReadBytes(4);//<0代表数据长度未知

            shx.Length = (l[0] << 24) | (l[1] << 16) | (l[2] << 8) | l[3];
            shx.Version = reader.ReadInt32();
            shx.geometryType = (GeoType)reader.ReadInt32();

            shx.xMin = reader.ReadDouble();
            shx.yMin = reader.ReadDouble();
            shx.xMax = reader.ReadDouble();
            shx.yMax = reader.ReadDouble();
            int blockCnt = (int)(reader.BaseStream.Length - 100) >> 3;
            shx.Blocks = new List<ShxBlock>(blockCnt);

            while (reader.PeekChar() != -1)
            {
                byte[] b = reader.ReadBytes(4);
                int offset = b[0] << 24 | b[1] << 16 | b[2] << 8 | b[3];

                b = reader.ReadBytes(4);
                int record = b[0] << 24 | b[1] << 16 | b[2] << 8 | b[3];

                shx.Blocks.Add(new ShxBlock()
                {
                    Offset = offset,
                    Length = record
                });
            }

            return shx;
        }

        public override void Dispose()
        {
            base.Dispose();
        }
    }
}
